package com.maweirdos.gulimall.product.exception;

import com.maweirdos.gulimall.common.exception.BizCodeEnum;
import com.maweirdos.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Maweirdos
 * @Date: 2024/3/16 10:48
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.maweirdos.gulimall.product.app")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        // 获取异常结果信息
        BindingResult bindingResult = e.getBindingResult();
        Map<Object, Object> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            log.error("数据校验出现问题，字段：{}，异常类型：{}，异常消息：{}", fieldError.getField(), fieldError.getClass(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errMap);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
